<template>
  <div>
    <van-nav-bar
      title="用户登录"
      left-text="返回"
      left-arrow
      @click-left="goBack"
    />
    <div class="register-panel">
      <van-field
        v-model="userName"
        label="用户名"
        icon="clear"
        placeholder="请输入用户名"
        required
        @click-icon="userName = ''"
        :error-message="userNameErrorMsg"
      />
      <van-field
        v-model="passWord"
        type="password"
        label="密码"
        placeholder="请输入密码"
        required
        @click-icon="passWord = ''"
        :error-message="passWordErrorMsg"
      />
      <div class="register-button">
        <van-button
          type="primary"
          size="large"
          @click="loginAction"
          :loading="isLoading"
          >马上登录</van-button
        >
      </div>
    </div>
  </div>
</template>

<script>
// 引入axios
import { mapMutations } from 'vuex'
import { LoginUser } from '@/api/api.config.js'
import { Toast } from 'vant'

export default {
  created() {
    if (this.$store.state.userInfo && this.$store.state.userInfo.userName) {
      this.$router.push('/')
      Toast.success('用户已经登录')
    }
  },
  data() {
    return {
      userName: '',
      passWord: '',
      isLoading: false,
      userNameErrorMsg: '', // 初始值为空 刚开始不做任何的提示
      passWordErrorMsg: '',
    }
  },
  methods: {
    ...mapMutations(['setUserInfo']),
    // 用户注册
    async loginUserFn() {
      try {
        let uesrInfo = {
          userName: this.userName,
          passWord: this.passWord,
        }
        this.isLoading = true
        let res = await LoginUser(uesrInfo)
        console.log(res)
        if (res.code === 500) {
          Toast.fail(res.message)
          this.isLoading = false
        } else if (res.code === 200) {
          Toast.success('登录成功')
          this.$router.push('/')
          this.$store.commit('setUserInfo', res.data)
        }
      } catch (error) {
        Toast.fail(error)
        this.isLoading = false
      }
    },
    // 用户注册校验
    checkForm() {
      let isOk = true
      if (this.userName.length < 6) {
        this.userNameErrorMsg = '用户名不能小于6位'
        isOk = false
      } else {
        this.userNameErrorMsg = ''
      }
      if (this.passWord.length < 6) {
        this.passWordErrorMsg = '密码不能小于6位'
        isOk = false
      } else {
        this.passWordErrorMsg = ''
      }
      return isOk
    },
    // 用户注册触发
    loginAction() {
      this.checkForm() && this.loginUserFn()
    },
    goBack() {
      this.$router.go(-1)
    },
  },
}
</script>

<style scoped>
.register-panel {
  width: 96%;
  border-radius: 5px;
  margin: 20px auto;
  padding-bottom: 50px;
}
.register-button {
  padding-top: 10px;
}
</style>
